const {
  verifyCaptcha
} = require('../../lib/utils/captcha')
const {
  EMAIL_SCENE,
  LOG_TYPE
} = require('../../common/constants')
const {
  ERROR
} = require('../../common/error')
/**
 * 发送邮箱验证码，可用于登录、注册、绑定邮箱、修改密码等操作
 * @tutorial
 * @param {Object} params
 * @param {String} params.email     邮箱
 * @param {String} params.captcha   图形验证码
 * @param {String} params.scene     使用场景
 * @returns
 */
module.exports = async function (params = {}) {
  const schema = {
    email: 'email',
    captcha: 'string',
    scene: 'string'
  }
  this.middleware.validate(params, schema)

  const {
    email,
    captcha,
    scene
  } = params

  if (!(Object.values(EMAIL_SCENE).includes(scene))) {
    throw {
      errCode: ERROR.INVALID_PARAM
    }
  }

  await verifyCaptcha.call(this, {
    scene: 'send-email-code',
    captcha
  })

  // 生成6位随机数字验证码
  const code = String(Math.floor(Math.random() * 1000000)).padStart(6, '0')
  const expiresIn = 180 // 3分钟有效期

  // 保存验证码到数据库
  await require('../../lib/utils/verify-code')
    .setEmailVerifyCode.call(this, {
      email,
      code,
      expiresIn,
      scene
    })

  try {
    // 读取配置
    const config = require('uni-config-center')({
      pluginId: 'uni-id'
    }).config()
    
    const emailConfig = config.service?.email || {}
    
    // 导入自定义邮件服务模块
    const emailService = require('../../lib/email-service')
    
    const sceneTexts = {
      'register': '注册账号',
      'login-by-email': '邮箱登录',
      'reset-pwd-by-email': '重置密码',
      'bind-email': '绑定邮箱'
    }
    
    await emailService.sendVerifyCode({
      to: email,
      code: code,
      expiresIn: Math.floor(expiresIn / 60),
      scene: sceneTexts[scene] || '验证',
      from: emailConfig.from,
      subject: emailConfig.subject || '验证码'
    })

    // 记录成功日志
    await this.middleware.uniIdLog({
      type: LOG_TYPE.SEND_EMAIL_CODE,
      success: true,
      email
    })

    console.log(`[EMAIL] 验证码已发送: ${email}, 场景: ${scene}, 验证码: ${code}`)

    return {
      errCode: 0,
      errMsg: '验证码发送成功'
    }
  } catch (error) {
    console.error('[EMAIL] 发送失败:', error)
    
    // 记录失败日志
    await this.middleware.uniIdLog({
      type: LOG_TYPE.SEND_EMAIL_CODE,
      success: false,
      email
    })

    throw {
      errCode: ERROR.SEND_EMAIL_CODE_FAILED,
      errMsg: '验证码发送失败：' + (error.message || '未知错误')
    }
  }
}
